package com.blb.community.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 帅帅
 * @Date 2022/6/27 16:09
 * @PackageName:com.blb._20220625springboot_jwt.utils
 * @ClassName: ResponseResult
 * @Description: 响应数据返回对象
 * @Version 1.0
 */
@Data
@NoArgsConstructor
public class ResponseResult<T> {


    /**
     * 响应状态
     */
    private ResponseStatus responseStatus;

    /**
     * 响应数据
     */
    private T data;

    public ResponseResult(ResponseStatus responseStatus, T data) {
        this.responseStatus = responseStatus;
        this.data = data;
    }

    /**
     * 返回成功对象
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ResponseResult<T> ok(T data) {
        return new ResponseResult<>(ResponseStatus.ok, data);
    }

    public static <T> ResponseResult<T> error(T data) {
        return new ResponseResult<>(ResponseStatus.ok, data);
    }

    public static <T> ResponseResult<T> error(ResponseStatus status, T data) {
        return new ResponseResult<T>(status, data);
    }

    /**
     * 返回错误的对象
     *
     * @param status
     * @return
     */
    public static ResponseResult<String> error(ResponseStatus status) {
        return new ResponseResult<>(status, status.getMessage());
    }

    public static void write(HttpServletResponse response, ResponseResult result) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String msg = new ObjectMapper().writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(msg);
        writer.close();
    }

}
